package admin.controllers;

import java.io.IOException;
import java.util.TreeMap;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import models.UserModel;

import admin.data.UserData;
import admin.forms.UserForm;

public class AddUserServlet extends HttpServlet {
	public void doGet(HttpServletRequest request, HttpServletResponse response)
		throws IOException {
		TreeMap check = new TreeMap();
		UserModel user = new UserModel();
		
		request.setAttribute("form", "add");
		request.setAttribute("check", check);
		request.setAttribute("user", user);
		try {
			request.getRequestDispatcher("/admin/pages/form_user.jsp").forward(request, response);
		} catch (ServletException e) {
			e.printStackTrace();
		}
	}
	
	public void doPost(HttpServletRequest request, HttpServletResponse response)
		throws IOException {
		UserData uData = new UserData();
		UserModel user = new UserModel();
		
		//Check value valid form
		UserForm userForm = new UserForm();
		TreeMap forms = (TreeMap) userForm.checkValid(request, user); 
		user = (UserModel) forms.get("user");
		TreeMap check = (TreeMap) forms.get("checkValid");
		
		if(check.size() == 0)
	    {
			uData.insert(user);
			request.setAttribute("success", "Add success user " + user.getUsername());
			user = new UserModel();
	    }
		
		request.setAttribute("form", "add");
		request.setAttribute("check", check);
		request.setAttribute("user", user);
		try {
			request.getRequestDispatcher("/admin/pages/form_user.jsp").forward(request, response);
		} catch (ServletException e) {
			e.printStackTrace();
		}
		
		
	}
}
